package ucp.projects.kraken.kamcenter.plugin;

import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import javax.imageio.ImageIO;

/**
 *
 * @author M. Cardinaux <matthieu.cardinaux at gmail.com>
 */
public final class CameraFrame implements Serializable{

    private static final long serialVersionUID = 911L;

    private String sourceName;
    private long timestamp;
    private transient BufferedImage image;

    public CameraFrame(String sourceName, long d, BufferedImage img) {
        this.sourceName = sourceName;
        this.timestamp = d;
        this.image = img;
    }

    public CameraFrame(String sourceName, BufferedImage img) {
        this(sourceName, System.currentTimeMillis(), img);
    }

    public CameraFrame(CameraFrame frame) {
        this.sourceName = frame.sourceName;
        this.timestamp = frame.timestamp;
        this.image = frame.image==null?null:copyBufferedImage(frame.image);
    }

    public long getTimestamp() {
        return timestamp;
    }

    public BufferedImage getImage() {
        return image;
    }

    public String getSourceName(){
        return sourceName;
    }

    public static BufferedImage copyBufferedImage(BufferedImage img) {
        ColorModel cm = img.getColorModel();
        WritableRaster wr = img.copyData(null);
        boolean iap = img.isAlphaPremultiplied();
        return new BufferedImage(cm, wr, iap, null);
    }

    public static BufferedImage convertToType(BufferedImage sourceImage,
            int targetType) {

        BufferedImage image;

        // if the source image is already the target type, return the source
        // image
        if (sourceImage.getType() == targetType) {
            image = sourceImage;
        }
        // otherwise create a new image of the target type and draw the new
        // image
        else {
            image = new BufferedImage(sourceImage.getWidth(),
                    sourceImage.getHeight(), targetType);
            image.getGraphics().drawImage(sourceImage, 0, 0, null);
        }

        return image;

    }

    private void writeObject(ObjectOutputStream out) throws IOException{
        out.defaultWriteObject();
        ImageIO.write(image, "jpeg", out);
    }

    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException{
        in.defaultReadObject();
        image = ImageIO.read(in);
    }



}
